package com.kgc.rb.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.rb.common.exception.CommonException;
import com.kgc.rb.common.tools.Constants;
import com.kgc.rb.common.tools.EmptyUtils;
import com.kgc.rb.common.tools.TokenTools;
import com.kgc.rb.dto.RbResult;
import com.kgc.rb.pojo.QgUser;
import com.kgc.rb.service.LocalUserService;
import com.kgc.rb.service.QgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


@Service

public class LocalUserServiceImpl implements LocalUserService {

    @Reference
    private QgUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public String login(String phone, String password) throws Exception {
        //如果代码能走到这里说明前面的验证没有问题
        QgUser qgUser = userService.getQgUserByCondition(phone, password);
        if (EmptyUtils.isEmpty(qgUser)) {
            return null;
        }
        //1.根据token:userid值去Redis中查询看一下是否有数据存在
        String oldToken = (String) redisTemplate.opsForValue().get(Constants.TOKEN_PREFIX + qgUser.getId());
        //说明redis中已经有该用户的数据，也就是 说这个用户已经登录过了
        if (EmptyUtils.isNotEmpty(oldToken)) {
            redisTemplate.delete(Constants.TOKEN_PREFIX + qgUser.getId());
            redisTemplate.delete(oldToken);
        }
        //1.生成token
        String token = Constants.TOKEN_PREFIX + TokenTools.createToken(qgUser.getId(), qgUser.getPhone());
        //redisTemplate:userid值作为key，token作为置存入redis中
        redisTemplate.opsForValue().set(Constants.TOKEN_PREFIX + qgUser.getId(), token, Constants.TOKEN_EXPIRE_TIME);

        //2.将token作为key用户的信息作为值保存到Redis中
        redisTemplate.opsForValue().set(token, qgUser);

        //如果代码能走到这里说明登录失败
        return token;
    }

    @Override
    public RbResult loginOut(String token) {
        //1.判断token是否为空
        if (EmptyUtils.isEmpty(token)) {
            return RbResult.build(CommonException.USER_NO_LOGIN.getCode(),
                    CommonException.USER_NO_LOGIN.getMessage());
        }
        //2.根据token去redis中获取用户的信息
        QgUser qgUser = (QgUser) redisTemplate.opsForValue().get(token);
        //3.在redis中删除key为token:1，以及key为token的数据
        redisTemplate.delete(Constants.TOKEN_PREFIX + qgUser.getId());
        redisTemplate.delete(token);
        return RbResult.ok();
    }
}
